<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="MySQL主从复制, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>MySQL主从复制 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/2.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">MySQL主从复制</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/MySQL-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6/">
                                <span class="chip bg-color">MySQL 主从复制</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/MySQL/" class="post-category">
                                MySQL
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-10-31
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-03-27
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    16 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="1-主从复制概述"><a href="#1-主从复制概述" class="headerlink" title="1. 主从复制概述"></a>1. 主从复制概述</h2><h3 id="1-1-如何提升数据库并发能力"><a href="#1-1-如何提升数据库并发能力" class="headerlink" title="1.1 如何提升数据库并发能力"></a>1.1 如何提升数据库并发能力</h3><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110757831.png" alt="image-20220327110757831" style="zoom:80%;" />

<p>此外，一般应用对数据库而言都是“ 读多写少”，也就说对数据库读取数据的压力比较大，有一个思路就是采用数据库集群的方案，做主从架构、进行读写分离，这样同样可以提升数据库的并发处理能力。但并不是所有的应用都需要对数据库进行主从架构的设置，毕竟设置架构本身是有成本的。</p>
<p>如果我们的目的在于提升数据库高并发访问的效率，那么首先考虑的是如何优化SQL和索引，这种方式简单有效；其次才是采用缓存的策略，比如使用 Redis将热点数据保存在内存数据库中，提升读取的效率；最后才是对数据库采用主从架构，进行读写分离。</p>
<h3 id="1-2-主从复制的作用"><a href="#1-2-主从复制的作用" class="headerlink" title="1.2 主从复制的作用"></a>1.2 主从复制的作用</h3><p>主从同步设计不仅可以提高数据库的吞吐量，还有以下 3 个方面的作用。<br>第1个作用：读写分离。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110803720.png" alt="image-20220327110803720" style="zoom:80%;" />

<p>第2个作用就是数据备份。<br>第3个作用是具有高可用性。</p>
<h2 id="2-主从复制的原理"><a href="#2-主从复制的原理" class="headerlink" title="2. 主从复制的原理"></a>2. 主从复制的原理</h2><p>Slave 会从Master 读取binlog 来进行数据同步。</p>
<h3 id="2-1-原理剖析"><a href="#2-1-原理剖析" class="headerlink" title="2.1 原理剖析"></a>2.1 原理剖析</h3><p>三个线程<br>实际上主从同步的原理就是基于 binlog 进行数据同步的。在主从复制过程中，会基于 3 个线程来操作，一个主库线程，两个从库线程。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110825816.png" alt="image-20220327110825816" style="zoom:80%;" />

<p>二进制日志转储线程（Binlog dump thread）是一个主库线程。当从库线程连接的时候， 主库可以将二进制日志发送给从库，当主库读取事件（Event）的时候，会在 Binlog 上加锁，读取完成之后，再将锁释放掉。从库 I/O 线程会连接到主库，向主库发送请求更新 Binlog。这时从库的 I/O 线程就可以读取到主库的二进制日志转储线程发送的 Binlog 更新部分，并且拷贝到本地的中继日志 （Relay log）。</p>
<p>从库 SQL 线程会读取从库中的中继日志，并且执行日志中的事件，将从库中的数据与主库保持同步</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110825816.png" style="zoom:80%;" />

<p>复制三步骤</p>
<ul>
<li>步骤1： Master 将写操作记录到二进制日志（ binlog ）。</li>
<li>步骤2： Slave 将Master 的binary log events拷贝到它的中继日志（ relay log ）；</li>
<li>步骤3： Slave 重做中继日志中的事件，将改变应用到自己的数据库中。 MySQL复制是异步的且串行化的，而且重启后从接入点开始复制。</li>
</ul>
<p>复制的问题</p>
<ul>
<li>复制的最大问题： 延时</li>
</ul>
<h3 id="2-2-复制的基本原则"><a href="#2-2-复制的基本原则" class="headerlink" title="2.2 复制的基本原则"></a>2.2 复制的基本原则</h3><ul>
<li>每个Slave 只有一个Master</li>
<li>每个Slave 只能有一个唯一的服务器ID</li>
<li>每个Master 可以有多个Slave</li>
</ul>
<h2 id="3-一主一从架构搭建"><a href="#3-一主一从架构搭建" class="headerlink" title="3. 一主一从架构搭建"></a>3. 一主一从架构搭建</h2><p>一台主机用于处理所有写请求，一台从机负责所有读请求，架构图如下：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110841832.png" alt="image-20220327110841832" style="zoom:80%;" />

<h3 id="3-1-准备工作"><a href="#3-1-准备工作" class="headerlink" title="3.1 准备工作"></a>3.1 准备工作</h3><p>1、准备2台CentOS 虚拟机<br>2、每台虚拟机上需要安装好MySQL (可以是MySQL8.0 )</p>
<p>说明：前面我们讲过如何克隆一台CentOS。大家可以在一台CentOS上安装好MySQL，进而通过克隆的方式复制出1台包含MySQL的虚拟机。</p>
<p>注意：克隆的方式需要修改新克隆出来主机的：① MAC地址 ② hostname ③ IP 地址 ④ UUID 。</p>
<p>此外，克隆的方式生成的虚拟机（包含MySQL Server），则克隆的虚拟机MySQL Server的UUID相同，必须修改，否则在有些场景会报错。比如： show slave status\G ，报如下的错误：</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">Last_IO_Error: Fatal error: The slave I&#x2F;O thread stops because master and slave have
equal MySQL server UUIDs; these UUIDs must be different for replication to work.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>修改MySQL Server 的UUID方式：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> /var/lib/mysql/auto.cnf
systemctl restart mysqld<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h3 id="3-2-主机配置文件"><a href="#3-2-主机配置文件" class="headerlink" title="3.2 主机配置文件"></a>3.2 主机配置文件</h3><p>建议mysql版本一致且后台以服务运行，主从所有配置项都配置在[mysqld] 节点下，且都是小写字母。<br>具体参数配置如下：</p>
<ul>
<li><p>必选</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#[必须]主服务器唯一ID</span>
server<span class="token operator">-</span>id<span class="token operator">=</span><span class="token number">1</span>
<span class="token comment">#[必须]启用二进制日志,指名路径。比如：自己本地的路径/log/mysqlbin</span>
log<span class="token operator">-</span>bin<span class="token operator">=</span>atguigu<span class="token operator">-</span>bin<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p>可选</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#[可选] 0（默认）表示读写（主机），1表示只读（从机）</span>
<span class="token keyword">read</span><span class="token operator">-</span>only<span class="token operator">=</span><span class="token number">0</span>
<span class="token comment">#设置日志文件保留的时长，单位是秒</span>
binlog_expire_logs_seconds<span class="token operator">=</span><span class="token number">6000</span>
<span class="token comment">#控制单个二进制日志大小。此参数的最大和默认值是1GB</span>
max_binlog_size<span class="token operator">=</span><span class="token number">200</span>M
<span class="token comment">#[可选]设置不要复制的数据库</span>
binlog<span class="token operator">-</span><span class="token keyword">ignore</span><span class="token operator">-</span>db<span class="token operator">=</span>test
<span class="token comment">#[可选]设置需要复制的数据库,默认全部记录。比如：binlog-do-db=atguigu_master_slave</span>
binlog<span class="token operator">-</span><span class="token keyword">do</span><span class="token operator">-</span>db<span class="token operator">=</span>需要复制的主数据库名字
<span class="token comment">#[可选]设置binlog格式</span>
binlog_format<span class="token operator">=</span>STATEMENT<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ul>
<p>binlog格式设置：</p>
<p>①： STATEMENT模式（基于SQL语句的复制(statement-based replication, SBR)）</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">binlog_format<span class="token operator">=</span>STATEMENT<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>每一条会修改数据的sql语句会记录到binlog中。这是默认的binlog格式。</p>
<ul>
<li>SBR 的优点：<ul>
<li>历史悠久，技术成熟</li>
<li>不需要记录每一行的变化，减少了binlog日志量，文件较小</li>
<li>binlog中包含了所有数据库更改信息，可以据此来审核数据库的安全等情况</li>
<li>binlog可以用于实时的还原，而不仅仅用于复制</li>
<li>主从版本可以不一样，从服务器版本可以比主服务器版本高</li>
</ul>
</li>
<li>SBR 的缺点：<ul>
<li>不是所有的UPDATE语句都能被复制，尤其是包含不确定操作的时候</li>
</ul>
</li>
<li>使用以下函数的语句也无法被复制：LOAD_FILE()、UUID()、USER()、FOUND_ROWS()、SYSDATE()(除非启动时启用了 –sysdate-is-now 选项)<ul>
<li>INSERT … SELECT 会产生比 RBR 更多的行级锁</li>
<li>复制需要进行全表扫描(WHERE 语句中没有使用到索引)的 UPDATE 时，需要比 RBR 请求更多的行级锁</li>
<li>对于有 AUTO_INCREMENT 字段的 InnoDB表而言，INSERT 语句会阻塞其他 INSERT 语句</li>
<li>对于一些复杂的语句，在从服务器上的耗资源情况会更严重，而 RBR 模式下，只会对那个发生变化的记录产生影响</li>
<li>执行复杂语句如果出错的话，会消耗更多资源</li>
<li>数据表必须几乎和主服务器保持一致才行，否则可能会导致复制出错</li>
</ul>
</li>
</ul>
<p>② ROW模式（基于行的复制(row-based replication, RBR)）</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token assign-left variable">binlog_format</span><span class="token operator">=</span>ROW<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>5.1.5版本的MySQL才开始支持，不记录每条sql语句的上下文信息，仅记录哪条数据被修改了，修改成什<br>么样了。</p>
<ul>
<li>RBR 的优点：<ul>
<li>任何情况都可以被复制，这对复制来说是最安全可靠的。（比如：不会出现某些特定情况下的存储过程、function、trigger的调用和触发无法被正确复制的问题）</li>
<li>多数情况下，从服务器上的表如果有主键的话，复制就会快了很多</li>
<li>复制以下几种语句时的行锁更少：INSERT … SELECT、包含 AUTO_INCREMENT 字段的 INSERT、没有附带条件或者并没有修改很多记录的 UPDATE 或 DELETE 语句</li>
<li>执行 INSERT，UPDATE，DELETE 语句时锁更少</li>
<li>从服务器上采用多线程来执行复制成为可能</li>
</ul>
</li>
<li>RBR 的缺点：<ul>
<li>binlog 大了很多</li>
<li>复杂的回滚时 binlog 中会包含大量的数据</li>
<li>主服务器上执行 UPDATE 语句时，所有发生变化的记录都会写到 binlog 中，而 SBR 只会写一次，这会导致频繁发生 binlog 的并发写问题</li>
<li>无法从 binlog 中看到都复制了些什么语句</li>
</ul>
</li>
</ul>
<p>③ MIXED模式（混合模式复制(mixed-based replication, MBR)）</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token assign-left variable">binlog_format</span><span class="token operator">=</span>MIXED<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>从5.1.8版本开始，MySQL提供了Mixed格式，实际上就是Statement与Row的结合。</p>
<p>在Mixed模式下，一般的语句修改使用statment格式保存binlog。如一些函数，statement无法完成主从复制的操作，则采用row格式保存binlog。<br>MySQL会根据执行的每一条具体的sql语句来区分对待记录的日志形式，也就是在Statement和Row之间选择一种。</p>
<h3 id="3-3-从机配置文件"><a href="#3-3-从机配置文件" class="headerlink" title="3.3 从机配置文件"></a>3.3 从机配置文件</h3><p>要求主从所有配置项都配置在my.cnf 的[mysqld] 栏位下，且都是小写字母。</p>
<ul>
<li>必选</li>
</ul>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#[必须]从服务器唯一ID</span>
server-id<span class="token operator">=</span><span class="token number">2</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ul>
<li>可选</li>
</ul>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#[可选]启用中继日志</span>
relay-log<span class="token operator">=</span>mysql-relay<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>重启后台mysql服务，使配置生效</p>
<blockquote>
<p>注意：主从机都关闭防火墙<br>service iptables stop #CentOS 6<br>systemctl stop firewalld.service #CentOS 7</p>
</blockquote>
<h3 id="3-4-主机：建立账户并授权"><a href="#3-4-主机：建立账户并授权" class="headerlink" title="3.4 主机：建立账户并授权"></a>3.4 主机：建立账户并授权</h3><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#在主机MySQL里执行授权主从复制的命令</span>
GRANT REPLICATION SLAVE ON *.* TO <span class="token string">'slave1'</span>@<span class="token string">'从机器数据库IP'</span> IDENTIFIED BY <span class="token string">'abc123'</span><span class="token punctuation">;</span>
<span class="token comment">#5.5,5.7</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>注意：如果使用的是MySQL8，需要如下的方式建立账户，并授权slave：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">USER</span> <span class="token string">'slave1'</span><span class="token variable">@'%'</span> IDENTIFIED <span class="token keyword">BY</span> <span class="token string">'123456'</span><span class="token punctuation">;</span>
<span class="token keyword">GRANT</span> <span class="token keyword">REPLICATION</span> SLAVE <span class="token keyword">ON</span> <span class="token operator">*</span><span class="token punctuation">.</span><span class="token operator">*</span> <span class="token keyword">TO</span> <span class="token string">'slave1'</span><span class="token variable">@'%'</span><span class="token punctuation">;</span>
<span class="token comment">#此语句必须执行。否则见下面。</span>
<span class="token keyword">ALTER</span> <span class="token keyword">USER</span> <span class="token string">'slave1'</span><span class="token variable">@'%'</span> IDENTIFIED <span class="token keyword">WITH</span> mysql_native_password <span class="token keyword">BY</span> <span class="token string">'123456'</span><span class="token punctuation">;</span>
flush <span class="token keyword">privileges</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<blockquote>
<p>注意：在从机执行show slave status\G时报错：<br>Last_IO_Error: error connecting to master ‘<a href="mailto:&#115;&#x6c;&#97;&#118;&#x65;&#49;&#x40;&#x31;&#57;&#50;&#x2e;&#x31;&#x36;&#56;&#x2e;&#x31;&#x2e;&#x31;&#x35;&#48;">&#115;&#x6c;&#97;&#118;&#x65;&#49;&#x40;&#x31;&#57;&#50;&#x2e;&#x31;&#x36;&#56;&#x2e;&#x31;&#x2e;&#x31;&#x35;&#48;</a>:3306’ - retry-time: 60 retries: 1<br>message: Authentication plugin ‘caching_sha2_password’ reported error: Authentication requires<br>secure connection.</p>
</blockquote>
<p>查询Master的状态，并记录下File和Position的值。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> master <span class="token keyword">status</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110851640.png" alt="image-20220327110851640" style="zoom:80%;" />

<ul>
<li>记录下File和Position的值</li>
</ul>
<blockquote>
<p>注意：执行完此步骤后不要再操作主服务器MySQL，防止主服务器状态值变化。</p>
</blockquote>
<h3 id="3-5-从机：配置需要复制的主机"><a href="#3-5-从机：配置需要复制的主机" class="headerlink" title="3.5 从机：配置需要复制的主机"></a>3.5 从机：配置需要复制的主机</h3><p>步骤1：从机上复制主机的命令</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">CHANGE MASTER <span class="token keyword">TO</span>
MASTER_HOST<span class="token operator">=</span><span class="token string">'主机的IP地址'</span><span class="token punctuation">,</span>
MASTER_USER<span class="token operator">=</span><span class="token string">'主机用户名'</span><span class="token punctuation">,</span>
MASTER_PASSWORD<span class="token operator">=</span><span class="token string">'主机用户名的密码'</span><span class="token punctuation">,</span>
MASTER_LOG_FILE<span class="token operator">=</span><span class="token string">'mysql-bin.具体数字'</span><span class="token punctuation">,</span>
MASTER_LOG_POS<span class="token operator">=</span>具体值<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>举例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">CHANGE MASTER TO
<span class="token assign-left variable">MASTER_HOST</span><span class="token operator">=</span><span class="token string">'192.168.1.150'</span>,MASTER_USER<span class="token operator">=</span><span class="token string">'slave1'</span>,MASTER_PASSWORD<span class="token operator">=</span><span class="token string">'123456'</span>,MASTER_LOG_F
<span class="token assign-left variable">ILE</span><span class="token operator">=</span><span class="token string">'atguigu-bin.000007'</span>,MASTER_LOG_POS<span class="token operator">=</span><span class="token number">154</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110900019.png" alt="image-20220327110900019" style="zoom:80%;" />

<p>步骤2：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">#启动slave同步</span>
<span class="token keyword">START</span> SLAVE<span class="token punctuation">;</span>	<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110912442.png" alt="image-20220327110912442" style="zoom:80%;" />

<p>如果报错：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110918272.png" alt="image-20220327110918272" style="zoom:80%;" />

<p>可以执行如下操作，删除之前的relay_log信息。然后重新执行 CHANGE MASTER TO …语句即可。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> reset slave<span class="token punctuation">;</span> <span class="token comment">#删除SLAVE数据库的relaylog日志文件，并重新启用新的relaylog文件</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>接着，查看同步状态：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SHOW</span> SLAVE <span class="token keyword">STATUS</span>\G<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110924648.png" alt="image-20220327110924648" style="zoom:80%;" />

<blockquote>
<p>上面两个参数都是Yes，则说明主从配置成功！</p>
</blockquote>
<p>显式如下的情况，就是不正确的。可能错误的原因有：</p>
<pre class="line-numbers language-tsx" data-language="tsx"><code class="language-tsx"><span class="token number">1.</span> 网络不通
<span class="token number">2.</span> 账户密码错误
<span class="token number">3.</span> 防火墙
<span class="token number">4.</span> mysql配置文件问题
<span class="token number">5.</span> 连接服务器时语法
<span class="token number">6.</span> 主服务器mysql权限<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110930917.png" alt="image-20220327110930917" style="zoom:80%;" />

<h3 id="3-6-测试"><a href="#3-6-测试" class="headerlink" title="3.6 测试"></a>3.6 测试</h3><p>主机新建库、新建表、insert记录，从机复制：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">DATABASE</span> atguigu_master_slave<span class="token punctuation">;</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> mytbl<span class="token punctuation">(</span>id <span class="token keyword">INT</span><span class="token punctuation">,</span>NAME <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> mytbl <span class="token keyword">VALUES</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">'zhang3'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> mytbl <span class="token keyword">VALUES</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span>@<span class="token variable">@hostname</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="3-7-停止主从同步"><a href="#3-7-停止主从同步" class="headerlink" title="3.7 停止主从同步"></a>3.7 停止主从同步</h3><p>停止主从同步命令：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">stop slave<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>如何重新配置主从</p>
<p>如果停止从服务器复制功能，再使用需要重新配置主从。否则会报错如下：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110938530.png" alt="image-20220327110938530" style="zoom:80%;" />

<p>重新配置主从，需要在从机上执行：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">stop slave<span class="token punctuation">;</span>
reset master<span class="token punctuation">;</span> <span class="token comment">#删除Master中所有的binglog文件，并将日志索引文件清空，重新开始所有新的日志文件(慎用)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h3 id="3-8-后续"><a href="#3-8-后续" class="headerlink" title="3.8 后续"></a>3.8 后续</h3><p>搭建主从复制：双主双从</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110944590.png" alt="image-20220327110944590" style="zoom:80%;" />

<h2 id="4-同步数据一致性问题"><a href="#4-同步数据一致性问题" class="headerlink" title="4. 同步数据一致性问题"></a>4. 同步数据一致性问题</h2><p>主从同步的要求：</p>
<ul>
<li>读库和写库的数据一致(最终一致)；</li>
<li>写数据必须写到写库；</li>
<li>读数据必须到读库(不一定)；</li>
</ul>
<h3 id="4-1-理解主从延迟问题"><a href="#4-1-理解主从延迟问题" class="headerlink" title="4.1 理解主从延迟问题"></a>4.1 理解主从延迟问题</h3><p>进行主从同步的内容是二进制日志，它是一个文件，在进行网络传输的过程中就一定会存在主从延迟（比如 500ms），这样就可能造成用户在从库上读取的数据不是最新的数据，也就是主从同步中的数据<br>不一致性问题。</p>
<h3 id="4-2-主从延迟问题原因"><a href="#4-2-主从延迟问题原因" class="headerlink" title="4.2 主从延迟问题原因"></a>4.2 主从延迟问题原因</h3><p>在网络正常的时候，日志从主库传给从库所需的时间是很短的，即T2-T1的值是非常小的。即，网络正常情况下，主备延迟的主要来源是备库接收完binlog和执行完这个事务之间的时间差。</p>
<p>主备延迟最直接的表现是，从库消费中继日志（relay log）的速度，比主库生产binlog的速度要慢。造<br>成原因：<br>  1、从库的机器性能比主库要差<br>  2、从库的压力大<br>  3、大事务的执行</p>
<p>举例1：一次性用delete语句删除太多数据</p>
<p>结论：后续再删除数据的时候，要控制每个事务删除的数据量，分成多次删除。</p>
<p>举例2：一次性用insert…select插入太多数据</p>
<p>举例:3：大表DDL</p>
<p>比如在主库对一张500W的表添加一个字段耗费了10分钟，那么从节点上也会耗费10分钟。</p>
<h3 id="4-3-如何减少主从延迟"><a href="#4-3-如何减少主从延迟" class="headerlink" title="4.3 如何减少主从延迟"></a>4.3 如何减少主从延迟</h3><p>若想要减少主从延迟的时间，可以采取下面的办法：</p>
<ol>
<li>降低多线程大事务并发的概率，优化业务逻辑</li>
<li>优化SQL，避免慢SQL， 减少批量操作，建议写脚本以update-sleep这样的形式完成。</li>
<li>提高从库机器的配置，减少主库写binlog和从库读binlog的效率差。</li>
<li>尽量采用短的链路，也就是主库和从库服务器的距离尽量要短，提升端口带宽，减少binlog传输的网络延时。</li>
<li>实时性要求的业务读强制走主库，从库只做灾备，备份。</li>
</ol>
<h3 id="4-4-如何解决一致性问题"><a href="#4-4-如何解决一致性问题" class="headerlink" title="4.4 如何解决一致性问题"></a>4.4 如何解决一致性问题</h3><p>如果操作的数据存储在同一个数据库中，那么对数据进行更新的时候，可以对记录加写锁，这样在读取的时候就不会发生数据不一致的情况。但这时从库的作用就是备份，并没有起到读写分离，分担主库读压力的作用。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327110952474.png" alt="image-20220327110952474" style="zoom:80%;" />

<p>读写分离情况下，解决主从同步中数据不一致的问题， 就是解决主从之间数据复制方式的问题，如果按照数据一致性从弱到强来进行划分，有以下 3 种复制方式。</p>
<h4 id="方法-1：异步复制"><a href="#方法-1：异步复制" class="headerlink" title="方法 1：异步复制"></a>方法 1：异步复制</h4><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111000502.png" alt="image-20220327111000502" style="zoom:80%;" />

<h4 id="方法-2：半同步复制"><a href="#方法-2：半同步复制" class="headerlink" title="方法 2：半同步复制"></a>方法 2：半同步复制</h4><img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111005317.png" alt="image-20220327111005317" style="zoom:80%;" />

<h4 id="方法-3：组复制"><a href="#方法-3：组复制" class="headerlink" title="方法 3：组复制"></a>方法 3：组复制</h4><p>异步复制和半同步复制都无法最终保证数据的一致性问题，半同步复制是通过判断从库响应的个数来决定是否返回给客户端，虽然数据一致性相比于异步复制有提升，但仍然无法满足对数据一致性要求高的场景，比如金融领域。MGR 很好地弥补了这两种复制模式的不足。</p>
<p>组复制技术，简称 MGR（MySQL Group Replication）。是 MySQL 在 5.7.17 版本中推出的一种新的数据复制技术，这种复制技术是基于 Paxos 协议的状态机复制。</p>
<p><strong>MGR 是如何工作的</strong></p>
<p>首先我们将多个节点共同组成一个复制组，在执行读写（RW）事务的时候，需要通过一致性协议层（Consensus 层）的同意，也就是读写事务想要进行提交，必须要经过组里“大多数人”（对应 Node 节点）的同意，大多数指的是同意的节点数量需要大于 （N/2+1），这样才可以进行提交，而不是原发起方一个说了算。而针对只读（RO）事务则不需要经过组内同意，直接 COMMIT 即可。</p>
<p>在一个复制组内有多个节点组成，它们各自维护了自己的数据副本，并且在一致性协议层实现了原子消息和全局有序消息，从而保证组内数据的一致性。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111011186.png" alt="image-20220327111011186" style="zoom:80%;" />

<p>MGR 将 MySQL 带入了数据强一致性的时代，是一个划时代的创新，其中一个重要的原因就是MGR 是基于 Paxos 协议的。Paxos 算法是由 2013 年的图灵奖获得者 Leslie Lamport 于 1990 年提出的，有关这个算法的决策机制可以搜一下。事实上，Paxos 算法提出来之后就作为分布式一致性算法被广泛应用，比如Apache 的 ZooKeeper 也是基于 Paxos 实现的。</p>
<h2 id="5-知识延伸"><a href="#5-知识延伸" class="headerlink" title="5. 知识延伸"></a>5. 知识延伸</h2><p>在主从架构的配置中，如果想要采取读写分离的策略，我们可以自己编写程序，也可以通过第三方的中间件来实现。</p>
<p>自己编写程序的好处就在于比较自主，我们可以自己判断哪些查询在从库上来执行，针对实时性要求高的需求，我们还可以考虑哪些查询可以在主库上执行。同时，程序直接连接数据库，减少了中间件层，相当于减少了性能损耗</p>
<p>采用中间件的方法有很明显的优势， 功能强大， 使用简单。但因为在客户端和数据库之间增加了中间件层会有一些性能损耗，同时商业中间件也是有使用成本的。我们也可以考虑采取一些优秀的开源工具。</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111018452.png" alt="image-20220327111018452" style="zoom:80%;" />

<p>① Cobar 属于阿里B2B事业群，始于2008年，在阿里服役3年多，接管3000+个MySQL数据库的schema,集群日处理在线SQL请求50亿次以上。由于Cobar发起人的离职，Cobar停止维护。<br>② Mycat 是开源社区在阿里cobar基础上进行二次开发，解决了cobar存在的问题，并且加入了许多新的功能在其中。青出于蓝而胜于蓝。<br>③ OneProxy 基于MySQL官方的proxy思想利用c语言进行开发的，OneProxy是一款商业收费的中间件。舍弃了一些功能，专注在性能和稳定性上。<br>④ kingshard 由小团队用go语言开发，还需要发展，需要不断完善。<br>⑤ Vitess 是Youtube生产在使用，架构很复杂。不支持MySQL原生协议，使用需要大量改造成本。<br>⑥ Atlas 是360团队基于mysql proxy改写，功能还需完善，高并发下不稳定。<br>⑦ MaxScale 是mariadb（MySQL原作者维护的一个版本） 研发的中间件<br>⑧ MySQLRoute 是MySQL官方Oracle公司发布的中间件</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111028024.png" alt="image-20220327111028024" style="zoom:80%;" />

<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111033428.png" alt="image-20220327111033428" style="zoom:80%;" />

<p>主备切换：</p>
<img src="https://cdn.jsdelivr.net/gh/kuangtf/PictureBed/img/image-20220327111039191.png" alt="image-20220327111039191" style="zoom:80%;" />

<ul>
<li>主动切换</li>
<li>被动切换</li>
<li>如何判断主库出问题了？如何解决过程中的数据不一致性问题？</li>
</ul>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Skyu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2021/10/31/MySQL/%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6/">https://kuangty.gitee.io/2021/10/31/MySQL/%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Skyu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/MySQL-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6/">
                                    <span class="chip bg-color">MySQL 主从复制</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/11/01/Redis/%E7%BC%93%E5%AD%98%E5%92%8C%E6%95%B0%E6%8D%AE%E5%BA%93%E4%B8%80%E8%87%B4%E6%80%A7%E9%97%AE%E9%A2%98/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/20.jpg" class="responsive-img" alt="缓存和数据库一致性问题，看这篇就够了">
                        
                        <span class="card-title">缓存和数据库一致性问题，看这篇就够了</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-11-01
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Redis/" class="post-category">
                                    Redis
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Redis-%E4%B8%80%E8%87%B4%E6%80%A7/">
                        <span class="chip bg-color">Redis 一致性</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/10/31/MySQL/BufferPool/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/18.jpg" class="responsive-img" alt="不会 MySQL 的 Buffer Pool，阿伟教你啊">
                        
                        <span class="card-title">不会 MySQL 的 Buffer Pool，阿伟教你啊</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-10-31
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/MySQL/" class="post-category">
                                    MySQL
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Buffer-Pool/">
                        <span class="chip bg-color">Buffer Pool</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
